<template>
  <el-form label-width="100" class="spuForm">
    <el-form-item label="SPU名称">
      <el-input v-model="spuParams.spuName" placeholder="请输入SPU名称"></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select placeholder="请选择SPU品牌" v-model="spuParams.tmId">
        <el-option v-for="item in AllTrademark" :key="item.id" :label="item.tmName" :value="item.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input v-model="spuParams.description" type="textarea" placeholder="请输入SPU描述"></el-input>
    </el-form-item>
    <!-- 照片墙 -->
    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="imgList"
        :on-preview="handlePictureCardPreview"  
        :on-remove="handleRemove"
        :before-upload="beforeAvatarUpload"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
      >

        <el-icon><Plus /></el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%;height: 100%;" />
      </el-dialog>
    </el-form-item>
    <!-- 销售属性 -->
    <el-form-item label="SPU销售属性">
      <el-select  v-model="saleAttrIdAndValueName" :placeholder="unSelectSaleAttr.length?`${unSelectSaleAttr.length}项还未选择`:'暂无可选择项'" style="margin-right: 10px;">
        <el-option v-for="item in unSelectSaleAttr" :key="item.id" :label="item.name" :value="`${item.id}:${item.name}`"></el-option>
      </el-select>
      <el-button :disabled="!unSelectSaleAttr.length || !saleAttrIdAndValueName" type="primary" icon="Plus" @click="addSaleAttr">添加属性</el-button>
      <!-- table -->
      <el-table border style="margin: 10px 0;" :data="saleAttr">
        <el-table-column width="80" align="center" label="序号" type="index"></el-table-column>
        <el-table-column prop="saleAttrName" width="120" label="销售属性名" ></el-table-column>
        <el-table-column  label="销售属性值" >
          <template #default="{row}">
            <el-tag @close="row.spuSaleAttrValueList.splice(index,1)" style="margin: 5px;" v-for="(item,index) in row.spuSaleAttrValueList" :key="item.id" closable class="mx-1"> 
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input @blur="toLook(row)" v-model="row.saleAttrValue" v-if="row.flag" size="small" style="width:100px;margin: 5px;" placeholder="请输入属性值"></el-input>
            <el-button v-else @click="toEdit(row)" type="primary" size="small" icon="Plus"></el-button>
          </template>
        </el-table-column>
        <el-table-column width="120" label="操作" >
          <template #default="{$index}">
            <el-button type="danger" size="small" icon="Delete" @click="saleAttr.splice($index,1)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      
    </el-form-item>
    <el-form-item>
      <el-button type="primary" :disabled="!saleAttr.length" @click="save">保存</el-button>
      <el-button type="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
const $emit = defineEmits<{
  changeScene: [{flag:number, params?:string}]
}>()
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { addOrUpdateSpu, reqAllTrademark, reqSpuImageList, reqSaleAttrList, reqAllSaleAttr } from '@/api/product/spu'
import type { SpuData, SaleAttrValue, SaleAttr, TrademarkList, SpuImageList, SaleAttrList, HasSaleAttrList } from '@/api/product/spu/type'
// const emit = defineEmits<{
//   (e: 'changeScene', scene: number):void
// }>()

// 收集还未选择的销售属性的id与属性值名字
const saleAttrIdAndValueName = ref('')

// 取消事件
const cancel = () => {
  $emit('changeScene', {flag: 0})
}
// 存储数据
const AllTrademark = ref<TrademarkList>([])
const imgList = ref<SpuImageList>([])
const saleAttr = ref<SaleAttrList>([])
const allSaleAttr = ref<HasSaleAttrList>([])

// 存储已有spu对象
const spuParams = ref<SpuData>({
  category3Id: '',
  spuName: '',
  description: '',
  tmId: '',
  spuImageList: [],
  spuSaleAttrList: []
})



// 初始化添加spu
const initAddSpu = async (c3Id:number|string) => {
  if(spuParams.value.id) {
    delete spuParams.value.id
  }
  // 清空数据
  Object.assign(spuParams.value, {
    category3Id: '',
    spuName: '',
    description: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: []
  })
  imgList.value = []
  saleAttr.value = []
  saleAttrIdAndValueName.value = ''


  spuParams.value.category3Id = c3Id
  // 获取全部品牌数据
  const res1 = await reqAllTrademark()
  AllTrademark.value = res1.data
  // 获取整个项目所有销售属性
  const res4 = await reqAllSaleAttr()
  allSaleAttr.value = res4.data
  
}

// 初始化修改spu 获取选择的spu下的 品牌列表 图片列表 销售属性列表
const initHasSpuData = async (row: SpuData) => {
  spuParams.value = row
  // 获取全部品牌数据
  const res1 = await reqAllTrademark()
  AllTrademark.value = res1.data
  // 获取spu图片
  const res2 = await reqSpuImageList(row.id as number)
  // v-model:file-list 中 key必须为name和url
  imgList.value = res2.data.map(item=> {
    return {
      name: item.imgName,
      url: item.imgUrl
    }
  })
  // 获取spu的销售属性
  const res3 = await reqSaleAttrList(row.id as number)
  saleAttr.value = res3.data
  // 获取整个项目所有销售属性
  const res4 = await reqAllSaleAttr()
  allSaleAttr.value = res4.data
}


// 照片墙预览
const dialogVisible = ref(false) //控制照片墙预览dialog
const dialogImageUrl = ref('') // 预览的图片
const handlePictureCardPreview = (file: any) => {
  // console.log(file) // 预览的图片地址
  dialogVisible.value = true
  dialogImageUrl.value = file.url
}

// 删除图片
const handleRemove = (rawFile:any) => {
  
}

// 上传之前
const beforeAvatarUpload = (rawFile:any) => {
  if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
    if(rawFile.size/1024/1024 < 4) {
      return true
    } else {
      ElMessage.error('文件大小不能超过4M')
      return false
    }
  } else {
    ElMessage.error('文件格式必须是PNG|JPG|GIF')
    return false
  }
}

// 计算出剩余可选的销售属性
const unSelectSaleAttr = computed(()=>{
  // 全部销售属性: arr1 颜色 版本 尺码 
  // 已有的销售属性 arr2 颜色 版本
  // 拿arr1中的颜色和arr2中的 颜色版本比 颜色等于颜色 every 返回 false
  // 拿arr1中的版本和arr2中的 颜色版本比 版本等于版本 every 返回 false
  // 拿arr1中的尺码和arr2中的 颜色版本比 尺码不等于版本,版本 every 返回 true
  const unSelectArr = allSaleAttr.value.filter(item => {
    return saleAttr.value.every(item1 => {
      return item.name != item1.saleAttrName
    })
  })
  return unSelectArr
})


// 添加销售属性
const addSaleAttr = () => {
  const [ baseSaleAttrId,saleAttrName ] = saleAttrIdAndValueName.value.split(':')
  const newSaleAttr:SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: []
  }
  // 追加到销售属性列表中
  saleAttr.value.push(newSaleAttr)
  saleAttrIdAndValueName.value = ''
}

// 属性值编辑模式
const toEdit = (row: SaleAttr) => {
  row.flag = true
  //收集销售属性值 将来添加到内部list中
  row.saleAttrValue = ''
}

// 失去焦点
const toLook = (row: SaleAttr) => {
  const { baseSaleAttrId, saleAttrValue } = row
  // 非法情况1 空值
  if(saleAttrValue?.trim() =='') {
    row.flag = false
    return ElMessage({
      type: 'error',
      message: '不能添加空的属性值'
    })
  }

  // 非法情况2 重复 这里和attr不同 这里Obj还没添加到row.spuSaleAttrValueList中 所以不需要排除自己
  const repeat = row.spuSaleAttrValueList.find(item => {
    return item.saleAttrValueName == saleAttrValue
  })

  if(repeat) {
    row.flag = false
    return ElMessage({
      type: 'error',
      message: '不能添加重复的值'
    })
  }


  const newSaleAttrValue:SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string
  }
  // 追加到 row.spuSaleAttrValueList
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  row.flag = false
}

// 保存
const save = async () => {
  // 整理参数 
  // 1.图片参数要改 新增的图片地址在response中
  spuParams.value.spuImageList = imgList.value.map((item:any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response&&item.response.data) || item.url
    }
  })
  // 2.整理销售属性数据
  spuParams.value.spuSaleAttrList = saleAttr.value
  const res = await addOrUpdateSpu(spuParams.value)
  if(res.code == 200) {
    ElMessage({
      type: 'success',
      message: spuParams.value.id?'更新成功': '添加成功'
    })
    $emit('changeScene', {flag:0,params: spuParams.value.id?'update':'add'})
  } else {
    ElMessage({
      type: 'error',
      message: spuParams.value.id?'更新失败': '添加失败'
    })
  }
}



defineExpose({
  initHasSpuData,
  initAddSpu
})
</script>

<style lang="scss" >
  .spuForm {

    .el-select {
      --el-select-width: 200px;
    }
  }
</style>
